package com.hsylient.demo04;

import lombok.NonNull;
import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 在静态代码块中对成员变量进行赋值，静态代码块在类加载的时候就会执行，这个时候对常量进行赋值。
 * 类加载只会加载一次，那么静态代码块也就只执行一次，提升了程序的性能
 */
public class JdbcUtil {

    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;
    private static final String CONFIG_FILE_NAME = "jdbc.properties";

    static {
        InputStream inputStream = null;
        try {
            inputStream = JdbcUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);
            Properties properties = new Properties();
            properties.load(inputStream);
            DRIVER = properties.getProperty("jdbc.driver");
            URL = properties.getProperty("jdbc.url");
            USERNAME = properties.getProperty("jdbc.username");
            PASSWORD = properties.getProperty("jdbc.password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @SneakyThrows
    public static Connection getConnection() {
        Class.forName(DRIVER);
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        return connection;
    }

    public static void closeResource(@NonNull Connection connection, @NonNull Statement statement, @NonNull ResultSet resultSet) {
        try {
            resultSet.close();
        } catch (SQLException throwAbles) {
            throwAbles.printStackTrace();
        }
        try {
            statement.close();
        } catch (SQLException throwAbles) {
            throwAbles.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void closeResource(@NonNull Connection connection, @NonNull Statement statement) {
        try {
            statement.close();
        } catch (SQLException throwAbles) {
            throwAbles.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException throwAbles) {
            throwAbles.printStackTrace();
        }
    }

    public static void closeResource(@NonNull Connection connection) {
        try {
            connection.close();
        } catch (SQLException throwAbles) {
            throwAbles.printStackTrace();
        }
    }
}
